<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2.用 vue 实现数据的双向绑定</title>
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>

<body>
    <div id="div1">
        <input type="text" v-model="name">
        <div> {{name}}</div>
    </div>
    <script>
        let el = document.getElementById('div1');
        let template = el.innerHTML;
        let _data = {
            name: 'hello world'
        };

        let data = new Proxy(_data, {
            set(obj, name, value) {
                obj[name] = value;
                render();
            }
        });

        render();

        function render() {
            el.innerHTML = template.replace(/\{\{\w+\}\}/g, str => {
                str = str.substring(2, str.length - 2);
                return _data[str];
            });

            Array.from(el.getElementsByTagName('input'))
                .filter(ele => ele.getAttribute('v-model'))
                .forEach(input => {
                    let name = input.getAttribute('v-model');
                    input.value = _data[name];

                    input.oninput = function () {
                        data[name] = this.value;
                    };
                });
        }
    </script>
</body>

</html>